package com.lzc.springMvcPart;

import com.alibaba.fastjson2.JSON;
import com.lzc.springMvcPart.annotation.Json;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;

public class JsonReturnResolver implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        Json json = returnType.getMethodAnnotation(Json.class);
        return json!=null;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        // 转json数据
        String json = JSON.toJSONString(returnValue);
        // 返回数据
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        response.getWriter().print(json);
        // 结束处理，不需要走视图解析
        mavContainer.setRequestHandled(true);
    }
}
